import React, { Component } from 'react';
import { message } from 'antd';
import PropTypes from 'prop-types';
import styles from './index.less';
import ReactUeditor from 'ifanrx-react-ueditor';
import { uploadFile } from '@/services/public';

window.UEDITOR_HOME_URL = 'https://worker-supervision-web.oss-cn-shanghai.aliyuncs.com/worker_supervision_oa/ueditor/';

class EditorText extends Component<any> {
  // props类型检查
  static propTypes = {
    //  监听选择
    onChange: PropTypes.func,

    defaultValue: PropTypes.string,
  };

  uploadImage = (e) => {
    return new Promise(async function (resolve, reject) {
      const file = e.target.files[0];
      const formData = new FormData();
      formData.append('file', file);

      uploadFile(formData)
        .then((res) => {
          if (res.success) {
            if (res.data && res.data.url) {
              resolve(res.data.url);
            } else {
              message.error('上传失败，请稍后重试！');
              reject();
            }
          } else {
            message.error(res.errMsg || '上传失败，请稍后重试！');
            reject();
          }
        })
        .catch(() => {
          reject();
        });
    });
  };

  handleEditChange = (value) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(value);
    }
  };

  render() {
    const { defaultValue } = this.props;
    
    return (
      <div className={styles.editorBox}>
        <ReactUeditor
          plugins={['uploadImage']}
          config={{
            allowDivTransToP: false,
          }}
          uploadImage={this.uploadImage}
          className={styles.editDefault}
          maxheight={360}
          value={defaultValue || ''}
          onChange={this.handleEditChange}
          ueditorPath={`https://worker-supervision-web.oss-cn-shanghai.aliyuncs.com/worker_supervision_oa/ueditor`}
        />
      </div>
    );
  }
}

// export default EditorText;
export default EditorText;
